import requests
import json
import base64

def encode_file_to_base64(file_path):
    """将文件编码为base64"""
    with open(file_path, 'rb') as f:
        return base64.b64encode(f.read()).decode('utf-8')

def call_qwen_omni_api():
    """调用Qwen Omni API示例"""
    url = "http://localhost:8000/v1/chat/completions"
    
    # 示例1: 纯文本对话
    text_payload = {
        "model": "Qwen2.5-Omni-3B",
        "messages": [
            {
                "role": "user",
                "content": "你好，请介绍一下你自己。"
            }
        ]
    }
    
    print("发送文本请求...")
    response = requests.post(url, json=text_payload)
    print("文本响应:", response.json())
    
    # 示例2: 视频分析（如果有视频文件）
    try:
        video_base64 = encode_file_to_base64("/root/projects/omni/fall.mp4")
        video_payload = {
            "model": "Qwen2.5-Omni-3B",
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "video",
                            "video": video_base64
                        }
                    ]
                }
            ],
            "use_audio_in_video": True
        }
        
        print("\n发送视频分析请求...")
        response = requests.post(url, json=video_payload)
        result = response.json()
        print("视频分析响应:", result)
        
        # 如果有音频响应，保存到文件
        if "choices" in result and result["choices"][0]["message"].get("audio"):
            audio_data = base64.b64decode(result["choices"][0]["message"]["audio"]["data"])
            with open("response_audio.wav", "wb") as f:
                f.write(audio_data)
            print("音频响应已保存到 response_audio.wav")
            
    except FileNotFoundError:
        print("视频文件不存在，跳过视频分析示例")

if __name__ == "__main__":
    call_qwen_omni_api()
